<template>
  <div class="page-account">
    <div class="stars"></div>
    <div class="stars2"></div>
    <div class="stars3"></div>
    <div class="login-container">
      <div class="login-form-wrapper">
        <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          autocomplete="on"
          label-position="left"
          @keyup.enter="handleLogin"
        >
          <el-form-item prop="account">
            <el-input
              ref="account"
              v-model="loginForm.account"
              prefix-icon="el-icon-user"
              placeholder="用户名"
              name="username"
              type="text"
              tabindex="1"
              autocomplete="on"
            />
          </el-form-item>

          <el-form-item prop="pwd">
            <el-input
              :key="passwordType"
              ref="pwd"
              v-model="loginForm.pwd"
              prefix-icon="el-icon-lock"
              :type="passwordType"
              placeholder="密码"
              name="pwd"
              tabindex="2"
              auto-complete="on"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>

          <el-form-item prop="code" class="captcha">
            <div class="captcha">
              <el-input
                ref="username"
                v-model="loginForm.code"
                style="width: 218px;"
                prefix-icon="el-icon-message"
                placeholder="验证码"
                name="username"
                type="text"
                tabindex="3"
                autocomplete="on"
              />
              <div class="imgs" @click="getCaptcha()"><img :src="captchatImg"></div>
            </div>
          </el-form-item>

          <el-button
            :loading="loading"
            type="primary"
            style="width:100%;margin-bottom:30px;"
            @click.native.prevent="handleLogin"
          >登录
          </el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { validUsername } from '@/utils/validate'
import "@/assets/js/canvas-nest.min.js";
import { getLoginPicApi, captchaApi, codeCheckApi } from '@/api/user'
import { getStoreStaff } from '@/libs/public'
import { getWXCodeByUrl, loginByWxCode } from "@/libs/wechat";
import { getWechatConfig } from "@/api/wxApi";
import { getToken, removeToken, setToken } from '@/utils/auth'
import Cookies from 'js-cookie'
export default {
  name: 'Login',
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('Please enter the correct user name'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6 || value.length >12) {
        callback(new Error('密码位数为6-12位'))
      } else {
        callback()
      }
    }
    return {
      captchatImg: '',
      swiperList: [],
      loginLogo: '',
      backgroundImages: '',
      backgroundImageMo: require("@/assets/imgs/bg.jpg"),
      fullWidth: document.body.clientWidth,
      swiperOption: {
        pagination: {
          el: '.pagination'
        },
        autoplay: {
          enabled: true,
          disableOnInteraction: false,
          delay: 3000
        }
      },
      loginForm: {
        account: 'admin', // admin
        pwd: '123456',
        key: '',
        code: '',
        wxCode: ''
      },
      loginRules: {
        account: [{ required: true, trigger: 'blur', message: '请输入用户名' }], // validator: validateUsername
        pwd: [{ required: true, trigger: 'blur', message: '请输入密码' }],
        code: [{ required: true, message: '请输入正确的验证码', trigger: 'blur' }]
      },
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {}
    }
  },
  watch: {
    fullWidth(val) {
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.screenWidth = val
        this.timer = true
        const that = this
        setTimeout(function() {
          // 打印screenWidth变化的值
          that.timer = false
        }, 400)
      }
    },
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
    const _this = this
    document.onkeydown = function(e) {
      if (_this.$route.path.indexOf('login') !== -1) {
        const key = window.event.keyCode
        if (key === 13) {
          _this.handleLogin()
        }
      }
    }
    window.addEventListener('resize', this.handleResize)
  },
  mounted() {
    this.getInfo()
    this.$nextTick(() => {
      if (this.screenWidth < 768) {
        document
          .getElementsByTagName("canvas")[0]
          .removeAttribute("class", "index_bg");
      } else {
        document.getElementsByTagName("canvas")[0].className = "index_bg";
      }
    });
    if (this.loginForm.account === '') {
      this.$refs.account.focus()
    } else if (this.loginForm.pwd === '') {
      this.$refs.pwd.focus()
    }
    this.getCaptcha()
    this.agentWeiXinLogin()
  },
  beforeCreate() {
    if (this.fullWidth < 768) {
      document
        .getElementsByTagName("canvas")[0]
        .removeAttribute("class", "index_bg");
    } else {
      document.getElementsByTagName("canvas")[0].className = "index_bg";
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  beforeDestroy: function() {
    window.removeEventListener('resize', this.handleResize)
    document
      .getElementsByTagName("canvas")[0]
      .removeAttribute("class", "index_bg");
  },
  methods: {
    agentWeiXinLogin(){ // 判断是否需要微信公众号登陆
      const _isWechat = this.$wechat.isWeixin();
      if (_isWechat) {
        let code = this.$route.query.code
        let state = this.$route.query.state
        let wxAuthPath = location.origin + '/login';
        //  如果没有code 去获取
        if(null == code){
          getWXCodeByUrl(wxAuthPath,'step1');
        }
        // 如果有state=step1 根据code去登陆
        if(state === 'step1'){
          loginByWxCode(code).then(res => {
            sessionStorage.setItem('token',res.token)
            this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
          }).catch(err => {
            // 如果登陆失败，那么输入账号登陆，重新获取code传递给后端做绑定
            getWXCodeByUrl(wxAuthPath,'step2');
          })
        }else if(state === 'step2'){
          this.loginForm.wxCode = code
        }

      }
      },
    onWechat(){
      let url = this.$route.query.redirect ? this.$route.query.redirect : '/dashboard'
      this.$wechat.oAuth(url, 'login')
    },
    handleResize(event) {
      this.fullWidth = document.body.clientWidth
      if (this.fullWidth < 768) {
        document
          .getElementsByTagName("canvas")[0]
          .removeAttribute("class", "index_bg");
      } else {
        document.getElementsByTagName("canvas")[0].className = "index_bg";
      }
    },
    getInfo() {
      getLoginPicApi().then(res => {
        this.swiperList = res.banner
        this.loginLogo = res.loginLogo
        this.backgroundImages = res.backgroundImage
        // Cookies.set('MerInfo', JSON.stringify(data))
      })
    },
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.pwd.focus()
      })
    },
    handleLogin() {
      const code = this.$route.query.code;
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          if(this.$wechat.isWeixin()){
            this.loginForm.wxCode = code
          }
          this.$store.dispatch('user/login', this.loginForm)
            .then(() => {
              this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              getStoreStaff()
              this.loading = false
            }).catch((err) => {
            this.loading = false
            if(this.$wechat.isPhone()) this.$dialog.error(err.message);
            this.getCaptcha()
          })
        } else {
          return false
        }
      })
    },
    getCaptcha() {
      captchaApi().then(( data ) => {
        this.captchatImg = data.code
        this.loginForm.key = data.key
      }).catch(({ message }) => {
        this.$message.error(message)
      })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    }
  }
}
</script>

<style lang="scss" scoped>
.page-account {
  width: 100%;
  height: 100vh;
  position: relative;
  background: radial-gradient(ellipse at bottom, #1b2735 0%, #090a0f 100%);
  overflow: hidden;
}

@function multiple-box-shadow($n) {
  $value: '#{random(2000)}px #{random(2000)}px #FFF';
  @for $i from 2 through $n {
    $value: '#{$value} , #{random(2000)}px #{random(2000)}px #FFF';
  }
  @return unquote($value);
}

$shadows-small:  multiple-box-shadow(700);
$shadows-medium: multiple-box-shadow(200);
$shadows-big:    multiple-box-shadow(100);

.stars {
  width: 1px;
  height: 1px;
  background: transparent;
  box-shadow: $shadows-small;
  animation: animStar 50s linear infinite;
    
  &:after {
    content: " ";
    position: absolute;
    top: 2000px;
    width: 1px;
    height: 1px;
    background: transparent;
    box-shadow: $shadows-small;
  }
}

.stars2 {
  width: 2px;
  height: 2px;
  background: transparent;
  box-shadow: $shadows-medium;
  animation: animStar 100s linear infinite;
    
  &:after {
    content: " ";
    position: absolute;
    top: 2000px;
    width: 2px;
    height: 2px;
    background: transparent;
    box-shadow: $shadows-medium;
  }
}

.stars3 {
  width: 3px;
  height: 3px;
  background: transparent;
  box-shadow: $shadows-big;
  animation: animStar 150s linear infinite;
    
  &:after {
    content: " ";
    position: absolute;
    top: 2000px;
    width: 3px;
    height: 3px;
    background: transparent;
    box-shadow: $shadows-big;
  }
}

@keyframes animStar {
  from {
    transform: translateY(0px);
  }
  to {
    transform: translateY(-2000px);
  }
}

.login-container {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 420px;
  padding: 35px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
  border: 1px solid rgba(255, 255, 255, 0.18);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.login-form-wrapper {
  width: 100%;
}

.login-form {
  width: 100%;

  :deep(.el-input__inner) {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    color: #fff;
    padding-right: 45px;

    &::placeholder {
      color: rgba(255, 255, 255, 0.6);
    }
  }

  :deep(.el-input__prefix) {
    color: rgba(255, 255, 255, 0.6);
  }
}

.show-pwd {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 16px;
  color: #333;
  cursor: pointer;
  user-select: none;
  z-index: 10;
  background: rgba(255, 255, 255, 0.8);
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  
  :deep(.svg-icon) {
    vertical-align: middle;
    font-size: 18px;
  }

  &:hover {
    background: rgba(255, 255, 255, 0.95);
  }
}

.captcha {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  
  .imgs {
    img {
      height: 36px;
      cursor: pointer;
      border-radius: 4px;
    }
  }
}

:deep(.el-button--primary) {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  backdrop-filter: blur(4px);
  
  &:hover {
    background: rgba(255, 255, 255, 0.3);
    border-color: rgba(255, 255, 255, 0.4);
  }
}
</style>
